package com.fanix5.javamvvm.network;

import android.accounts.NetworkErrorException;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public abstract class BaseObserver<T> implements Observer<T> {

    protected Disposable disposable;
    @Override
    public  void onSubscribe(Disposable d) {
        disposable = d;
    }

    @Override
    public void onNext(T result) {

        onSuccess(result);
    }

    @Override
    public void onError(Throwable e) {

        onFailure(ServerException.handleException(e).getMessage(), e instanceof ConnectException
                || e instanceof TimeoutException
                || e instanceof NetworkErrorException
                || e instanceof UnknownHostException);

        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }

    }

    /**
     * Notifies the Observer that the {@link Observable} has finished sending push-based notifications.
     * <p>
     * The {@link Observable} will not call this method if it calls {@link #onError}.
     * * 请求成功了才会调用 onComplete
     * onError 时不会调用
     */
    @Override
    public void onComplete() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    /**
     * 请求成功返回
     *
     * @param result 服务器返回数据
     */
    public abstract void onSuccess(T result);

    /**
     * 请求失败返回
     *
     * @param errMsg     失败信息
     * @param isNetError 是否是网络异常
     */
    public abstract void onFailure(String errMsg, boolean isNetError);




}
